//
//  JMPaddingView.m
//  NewiOSProject
//
//  Created by li on 2023/9/4.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "PaddingView.h"
@interface PaddingView()
@property(nonatomic, strong, nullable) NSLayoutConstraint *paddingLeft;
@property(nonatomic, strong, nullable) NSLayoutConstraint *paddingRight;
@property(nonatomic, strong, nullable) NSLayoutConstraint *paddingTop;
@property(nonatomic, strong, nullable) NSLayoutConstraint *paddingBottom;

@end

@implementation PaddingView

+ (PaddingView *)initWithContentView:(UIView *)content edgeInsets:(UIEdgeInsets)edgeInsets {
    
    PaddingView *paddingView = [PaddingView new];
//    paddingView.translatesAutoresizingMaskIntoConstraints = NO;
    paddingView.backgroundColor = [UIColor clearColor];
    paddingView.content = content;
    
    paddingView.edgeInsets = edgeInsets;
    
    return paddingView;
}

- (PaddingView *)then:(Configure)configure {
    if (configure != nil) {
        configure(self);
    }
    return self;
}

- (void)setContent:(UIView *)content {
    
    if (_content != nil) {
        [_content removeFromSuperview];
    }
    _content = content;
    
    content.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:content];
    
    self.paddingTop = [self.topAnchor constraintEqualToAnchor:content.topAnchor constant: -self.edgeInsets.top];
    self.paddingLeft = [self.leftAnchor constraintEqualToAnchor:content.leftAnchor constant: -self.edgeInsets.left];
    self.paddingRight = [self.rightAnchor constraintEqualToAnchor:content.rightAnchor constant: self.edgeInsets.right];
    self.paddingBottom = [self.bottomAnchor constraintEqualToAnchor:content.bottomAnchor constant: self.edgeInsets.bottom];
    
    self.paddingTop.active = YES;
    self.paddingLeft.active = YES;
    self.paddingBottom.active = YES;
    self.paddingRight.active = YES;
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets {
    _edgeInsets = edgeInsets;
    
    self.paddingTop.constant = -edgeInsets.top;
    self.paddingLeft.constant = -edgeInsets.left;
    self.paddingRight.constant = edgeInsets.right;
    self.paddingBottom.constant = edgeInsets.bottom;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
